package web.pre;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;


import entity.News;
import entity.Order;
import entity.OrderDetail;
import entity.Product;
import entity.ProductCategory;
import entity.User;
import entity.UserAddress;
import service.NewsService;
import service.OrderDetailService;
import service.OrderService;
import service.ProductCategoryService;
import service.ProductService;
import service.UserAddressSerivce;
import utils.ReturnResult;
import utils.ShoppingCart;
import utils.ShoppingCartItem;
import utils.StringUtils;


public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductService productService = new ProductService();
       
	private UserAddressSerivce userAddressService = new UserAddressSerivce();
	
	public ProductCategoryService prcat=new ProductCategoryService();

	public ProductService  pro=new ProductService();
	
	private OrderService orderService = new OrderService();
	
	private OrderDetailService orderDetailService = new OrderDetailService();
	
	public NewsService news=new NewsService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null && action.length()>0) {
			switch (action) {
			case "add":
				add(request,response);
				break;
			case "toSettlement":
				toSettlement(request,response);
				break;
			case "settlement1":
				settlement1(request,response);
				break;
			case "modCart":
				modCart(request,response);
				break;
			case "settlement2":
				settlement2(request,response);
				break;
			case "settlement3":
				settlement3(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}
	
	private void settlement3(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
    	ReturnResult result = new ReturnResult();
    	ShoppingCart cart = getCart(request);
        User user = (User) request.getSession().getAttribute("user");
        
        //检查库存
        boolean hasStock = true; 
        Iterator<ShoppingCartItem> iterator = cart.getItems().values().iterator();
        while (iterator.hasNext()) {
			ShoppingCartItem item = (ShoppingCartItem) iterator.next();
			
			Product product=productService.findById(item.getProduct().getId());
			
			if(product.getStock()<item.getQuantity()){
				result.setMessage(product.getName()+"商品数量不足");
				hasStock = false;
				break;
	        }
		}
        if (hasStock) {
        	//新增地址
            String addressId=request.getParameter("addressId");
            String newAddress=request.getParameter("newAddress");
            String newRemark=request.getParameter("newRemark");
            UserAddress userAddress=new UserAddress();
            if(addressId.equals("-1")){
                userAddress.setRemark(newRemark);
                userAddress.setAddress(newAddress);
                userAddress.setId(userAddressService.addUserAddress(user.getId(),newAddress,newRemark));
            }else{
                userAddress=userAddressService.findById(Integer.parseInt(addressId));
            }
            
            //生成订单
            //Order order = orderService.payShoppingCart(cart,user,userAddress.getAddress());
            //增加订单
            Order order = new Order();
            order.setUserId(user.getId());
            order.setLoginName(user.getLoginName());
            order.setUserAddress(userAddress.getAddress());
            order.setCreateTime(new Date());
            order.setCost(cart.getSum());
            order.setSerialNumber(StringUtils.randomUUID());
            int id= orderService.add(order);
            order.setId(id);
            //增加订单对应的明细信息
            iterator = cart.getItems().values().iterator();
            while (iterator.hasNext()) {
    			ShoppingCartItem item = (ShoppingCartItem) iterator.next();
    			OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(order.getId());
                orderDetail.setCost(item.getCost());
                orderDetail.setProductId(item.getProduct().getId());
                orderDetail.setQuantity(item.getQuantity());
                orderDetailService.add(orderDetail);
                //更新商品表的库存
                productService.procount(item.getProduct().getId(), item.getQuantity());
    			
    		}
            
            //清空购物车
            request.getSession().removeAttribute("cart");
            request.setAttribute("currentOrder", order);
            request.getRequestDispatcher("settlement3.jsp").forward(request, response);
		
            String jsonStr = JSON.toJSONString(result);
    		
    		out.print(jsonStr);
    		
    		out.flush();
    		out.close();
        }
	}

	private void settlement2(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		// TODO Auto-generated method stub
        User loginUser = (User) request.getSession().getAttribute("user");
		
		List<UserAddress> userAddressList = userAddressService.findByUserId(loginUser.getId());
		
		request.setAttribute("userAddressList", userAddressList);
		
		request.getRequestDispatcher("settlement2.jsp").forward(request, response);
	}

	private void modCart(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		// TODO Auto-generated method stub
        PrintWriter out = response.getWriter();
		
		ReturnResult result = new ReturnResult();
    	HttpSession session = request.getSession();
        String id = request.getParameter("entityId");
        String quantityStr = request.getParameter("quantity");
        ShoppingCart cart = getCart(request);
    	
        cart.modifyCart(Integer.parseInt(id), Integer.parseInt(quantityStr));
        
        session.setAttribute("cart", cart);//全部的商品
        result.setMessage("操作成功");
        result.setStatus(1);
        String jsonStr = JSON.toJSONString(result);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
	}
	private void settlement1(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		// TODO Auto-generated method stub
		ShoppingCart cart = getCart(request);
    	request.getSession().setAttribute("cart",cart);
    	request.getRequestDispatcher("settlement1.jsp").forward(request, response);
	}
	private ShoppingCart getCart(HttpServletRequest request){
		HttpSession session = request.getSession();
		//从session中拿购物车数据
    	ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("cart", cart);
        }
        return cart;
	}
	private void toSettlement(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException   {
		// TODO Auto-generated method stub
		List<ProductCategory> listProductCategory =prcat.prcatList();
		request.setAttribute("listProductCategory", listProductCategory);
		List<News> NewsList = news.NewsList();
		request.setAttribute("NewsList", NewsList);
		request.getRequestDispatcher("toSettlement.jsp").forward(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
       
        
        int id = Integer.parseInt(request.getParameter("entityId"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        
        //查询出商品
        Product product = productService.findById(id);
        
        //从session中拿购物车数据--
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("cart", cart);
        }
        
        //向购物车中添加商品
        cart.addItem(product, quantity);
        
        session.setAttribute("cart", cart);
        ReturnResult result = new ReturnResult();
        result.setMessage("已加入购物车");
        result.setStatus(1);
        String jsonStr = JSON.toJSONString(result);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
